Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds index usage info to get_index_information(include_stats=True) #5320

Merged
merged 1 commit into from
Dec 28, 2024

Conversation

brimoor
Copy link
Contributor

@brimoor brimoor commented Dec 27, 2024

Change log

  • Adds index usage info to get_index_information(include_stats=True)
  • Replaces collstats() calls with the $collStats aggregation, as the former has been deprecated since MongoDB v6.2
  • Removes the unused Dataset._frame_indexes property

Example usage

import fiftyone as fo
import fiftyone.zoo as foz

dataset = foz.load_zoo_dataset("quickstart")

dataset.create_index([("id", 1), ("uniqueness", 1)])

# Use the indexes
_ = dataset[dataset.first().id]
_ = dataset[dataset.first().filepath]
_ = dataset._max("created_at")
_ = dataset._max("last_modified_at")
_ = len(dataset.select(dataset.take(10)).sort_by("uniqueness", create_index=False))

fo.pprint(dataset.get_index_information(include_stats=True))
{
    'id': {
        'v': 2,
        'key': [('_id', 1)],
        'size': 4096,
        'accesses': {
            'ops': 1,
            'since': datetime.datetime(2024, 12, 27, 2, 19, 24, 610000),
        },
    },
    'filepath': {
        'v': 2,
        'key': [('filepath', 1)],
        'size': 4096,
        'accesses': {
            'ops': 1,
            'since': datetime.datetime(2024, 12, 27, 2, 19, 24, 652000),
        },
    },
    'created_at': {
        'v': 2,
        'key': [('created_at', 1)],
        'size': 4096,
        'accesses': {
            'ops': 1,
            'since': datetime.datetime(2024, 12, 27, 2, 19, 24, 696000),
        },
    },
    'last_modified_at': {
        'v': 2,
        'key': [('last_modified_at', 1)],
        'size': 4096,
        'accesses': {
            'ops': 1,
            'since': datetime.datetime(2024, 12, 27, 2, 19, 24, 738000),
        },
    },
    '_id_1_uniqueness_1': {
        'v': 2,
        'key': [('_id', 1), ('uniqueness', 1)],
        'size': 24576,
        'accesses': {
            'ops': 1,
            'since': datetime.datetime(2024, 12, 27, 2, 19, 28, 896000),
        },
    },
}

collstats -> $collStats migration

import fiftyone as fo
import fiftyone.core.odm as foo

dataset = fo.Dataset()

db = foo.get_db_conn()
cs1 = db.command("collstats", dataset._sample_collection_name)
cs2 = dataset._sample_collstats()

assert cs1["storageSize"] == cs2["storageSize"]
assert cs1["size"] == cs2["size"]
assert cs1["count"] == cs2["count"]
assert cs1["indexBuilds"] == cs2["indexBuilds"]
assert cs1["indexSizes"] == cs2["indexSizes"]

Summary by CodeRabbit

  • New Features

    • Enhanced index information retrieval with detailed statistics including size, usage, and build status.
    • Introduced a new method for collecting structured collection statistics using an aggregation framework.
  • Bug Fixes

    • Improved assertions in unit tests to validate additional index statistics.
  • Refactor

    • Updated method calls to streamline collection statistics retrieval.
    • Renamed test method for clarity.

@brimoor brimoor added the feature Work on a feature request label Dec 27, 2024
@brimoor brimoor requested a review from kaixi-wang December 27, 2024 02:25
Copy link
Contributor

coderabbitai bot commented Dec 27, 2024

Walkthrough

The pull request introduces enhancements to index information retrieval in the FiftyOne library. The changes focus on expanding the get_index_information method to provide more comprehensive index statistics. A new function _get_collstats is added to the Dataset class to retrieve collection statistics using an aggregation pipeline, replacing previous direct database connection methods. The modifications aim to improve the detail and structure of index-related information, allowing users to access more insights about index performance and storage.

Changes

File Change Summary
fiftyone/core/collections.py Updated get_index_information method to include index size, usage, and build status when include_stats=True
fiftyone/core/dataset.py Added _get_collstats function, replaced _sample_collstats and _frame_collstats calls, removed _frame_indexes property
tests/unittests/dataset_tests.py Renamed test_index_sizes to test_index_stats, updated assertions to check additional index statistic keys

Possibly related PRs

  • Fix sidebar indexes #5143: Updates to get_index_information() call with include_stats=True, directly related to the index statistics enhancement

Suggested reviewers

  • benjaminpkane
  • CamronStaley
  • minhtuev

Poem

🐰 Indexes dancing with grace,
Stats unfurling at lightning pace
Metrics bloom like spring's first flower
Code evolves with newfound power
Rabbit's wisdom: knowledge is might! 📊

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
tests/unittests/dataset_tests.py (2)

Line range hint 680-681: Consider verifying unique indexing constraints.

You create two indexes on the same field (gt.detections.label and frames.gt.detections.label). If the code or future changes require uniqueness or partial indexes, explicitly test those aspects so that incorrect index usage does not slip by undetected.


Line range hint 697-700: Validate structure of index statistics.

By checking 'size', 'ops', and 'since' keys, you confirm critical fields exist. Consider additional type or range checks (e.g., verifying 'ops' is an integer) to tighten correctness if needed.

fiftyone/core/collections.py (1)

Line range hint 9509-9566: Architecture advice for index statistics

The implementation provides valuable index usage information but could benefit from some additional features:

  1. Consider caching the index stats for a configurable duration to avoid frequent aggregation queries
  2. Add helper methods to analyze index usage patterns and provide recommendations
  3. Consider adding index size thresholds/alerts for large indexes
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 18dde78 and 1ec93f5.

📒 Files selected for processing (3)
  • fiftyone/core/collections.py (3 hunks)
  • fiftyone/core/dataset.py (2 hunks)
  • tests/unittests/dataset_tests.py (2 hunks)
🔇 Additional comments (9)
tests/unittests/dataset_tests.py (3)

674-674: Good test naming.

The descriptive method name clearly conveys the purpose of testing index statistics.


675-677: Efficient sample setup.

Reusing the same gt object across both the sample and its frames is a straightforward approach, but ensure this does not unintentionally mutate gt if future tests modify the label object in-place.


Line range hint 695-696: Comprehensive index presence checks.

These lines effectively verify that all expected indexes have indeed been created. This is a robust assertion step that ensures the test can catch regressions where indexes are removed or renamed.

fiftyone/core/dataset.py (2)

1205-1205: Ensure _sample_collection is never None

If _sample_collection is unexpectedly None or invalid, this line would raise an error. Consider verifying that the attribute is properly initialized before returning its stats.


1211-1211: Initialize frame collection before usage

If _frame_collection is None for non-video datasets, this call may raise an exception. Consider returning early or adding a check before calling _get_collstats.

fiftyone/core/collections.py (4)

9509-9510: Documentation improvement for include_stats parameter

The docstring update accurately reflects that the method now returns size, usage and build status information for each index when include_stats=True.


9531-9537: Added index usage statistics via $indexStats aggregation

The code now retrieves index usage statistics by using MongoDB's $indexStats aggregation operator, which provides information about how indexes are being used. This is a good addition that helps users understand index utilization patterns.


9560-9566: Consistent implementation of index stats for frame collections

The same index usage statistics gathering logic is properly applied to frame collections, maintaining consistency with the sample collection implementation.


Line range hint 9509-9566: Verify index stats aggregation performance

The added $indexStats aggregation could potentially impact performance on large collections. Let's verify this:

✅ Verification successful

$indexStats aggregation is safe to use

Based on the codebase analysis, the $indexStats aggregation is safely implemented and well-tested:

  • The feature is used only to gather metadata about existing indexes (size, usage, build status) and not for querying data
  • It's part of the core MongoDB functionality for index management
  • The implementation is covered by unit tests in tests/unittests/dataset_tests.py with test_index_stats
  • The aggregation is only executed when explicitly requested via include_stats=True parameter
  • The operation is lightweight as it only returns index metadata from MongoDB's system collections
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if indexStats aggregation is performant on large collections

# Look for large collections (>100k documents)
mongo_expr='{"$expr": {"$gt": [{"$size": "$samples"}, 100000]}}'
rg --json "$mongo_expr"

# Look for collections with many indexes
ast-grep --pattern 'create_index($$$)'

Length of output: 300


Script:

#!/bin/bash
# Search for index creation patterns and performance considerations
rg -A 3 "create_index\(" 

# Look for any performance-related comments or documentation about indexStats
rg -i "indexstats|performance|large collection"

# Check if there are any existing performance tests related to indexes
fd -e py test | xargs rg -l "index.*test|test.*index"

Length of output: 71279

fiftyone/core/dataset.py Show resolved Hide resolved
@@ -9528,6 +9528,13 @@ def get_index_information(self, include_stats=False):
if key in sample_info:
sample_info[key]["in_progress"] = True

for d in self._dataset._sample_collection.aggregate(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wondering if it would be useful to pull this out and make this a function that accepts the collection name as an arg to allow for creating something like an admin dashboard to manage indexes across datasets without needing to load each dataset

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The use case makes sense 👍 I'd suggest we consider whether a potential refactor adds clarity at that time

@brimoor brimoor merged commit 30b7469 into develop Dec 28, 2024
14 checks passed
@brimoor brimoor deleted the index-acceses branch December 28, 2024 21:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Work on a feature request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants